import axios from 'axios'
import config from './config.js'
import Cookies from 'cookies-js'

const instance = axios.create({
  baseURL: config.baseURL,
  headers: config.headers,
  transformResponse: [function (data) {}]
})

instance
  .interceptors
  .request
  .use(config => {
    return config
  }, error => {
    if (error.code === 'ECONNABORTED' && error.message.index('timeout') !== -1) {

    }

    const errorInfo = error.response
    console.log(errorInfo)
    return error
  })

instance
  .interceptors
  .response
  .use(response => {
    let data
    if (response.data === undefined) {
      data = response.request.responseText
    } else {
      data = response.data
    }
    data ? (data = JSON.parse(data)) : (data = {})

    if (data.error && data.error.code === 401) {
      Cookies.set('username', undefined)
      Cookies.set('roleId', undefined)
      Cookies.set('mobile', undefined)
      window.location.href = '/'
    }

    return data
  }, err => {
    if (err && err.response) {
      switch (err.response.status) {
        case 400:
          err.message = '请求错误'
          break
        case 401:
          err.message = '未授权，请登录'
          break
        case 404:
          err.message = '404'
          break
        default:
      }
    }

    console.log(err.message)
    return err
  })

export default instance
